import 'dart:typed_data';

import '../bean/BleBeanInterface.dart';
import 'CheckBleSupportInterface.dart';
import 'OnBleConnectListener.dart';
import 'OnBleDataListener.dart';
import 'OnBleScanListener.dart';
import 'OnOtaListener.dart';

mixin BleEvent implements OnBleConnectListener, OnBleScanListener, OnOtaListener, OnBleDataListener {
  ///连接事件监听
  final List<OnBleConnectListener> _connectListeners = [];

  ///扫描回调监听
  final List<OnBleScanListener> _scantListeners = [];

  ///扫描到的设备
  final List<BleBeanInterface> _bleBeans = [];

  ///ota相关的回调监听
  final List<OnOtaListener> _otaListeners = [];

  ///数据监听
  final List<OnBleDataListener> _bleDataListeners = [];

  ///设备兼容检测
  final List<CheckBleSupportInterface> _checkBleSupport = [];

  List<CheckBleSupportInterface> get checkBleSupport => _checkBleSupport;

  //是否正在扫描
  bool _isScanning = false;

  //是否正在连接
  bool _isConnecting = false;

   set isConnecting(bool value) {
    _isConnecting = value;
  }

  bool get isConnecting => _isConnecting;

  void addDataListener(OnBleDataListener listener) {
    if (!_bleDataListeners.contains(listener)) {
      _bleDataListeners.add(listener);
    }
  }

  void removeDataListener(OnBleDataListener listener) {
    _bleDataListeners.remove(listener);
  }

  void addScanListener(OnBleScanListener listener) {
    if (!_scantListeners.contains(listener)) {
      _scantListeners.add(listener);
    }
  }

  void removeScanListener(OnBleScanListener listener) {
    _scantListeners.remove(listener);
  }

  void addConnectListener(OnBleConnectListener listener) {
    if (!_connectListeners.contains(listener)) {
      _connectListeners.add(listener);
    }
  }

  void removeConnectListener(OnBleConnectListener listener) {
    _connectListeners.remove(listener);
  }

  void addOtaListener(OnOtaListener listener) {
    if (!_otaListeners.contains(listener)) {
      _otaListeners.add(listener);
    }
  }

  void removeOtaListener(OnOtaListener listener) {
    _otaListeners.remove(listener);
  }

  void addCheckBleSupport(CheckBleSupportInterface checkBleSupport) {
    if (!_checkBleSupport.contains(checkBleSupport)) {
      _checkBleSupport.add(checkBleSupport);
    }
  }

  void removeCheckBleSupport(CheckBleSupportInterface checkBleSupport) {
    _checkBleSupport.remove(checkBleSupport);
  }

  List<BleBeanInterface> get bleBeans {
    return _bleBeans;
  }

  ///清空未连接的蓝牙
  void clearUnConnect() {
    List<BleBeanInterface> list = [];
    for (var bean in _bleBeans) {
      if (bean.isConnect) {
        list.add(bean);
      }
    }
    _bleBeans.clear();
    _bleBeans.addAll(list);
    notifyListener();
  }

  ///蓝牙是否正在扫描
  bool isScanning() {
    return _isScanning;
  }

  ///开始扫描
  @override
  void onStartScan() {
    _isScanning = true;
    for (var listener in _scantListeners) {
      listener.onStartScan();
    }
  }

  ///停止扫描
  @override
  void onStopScan() {
    _isScanning = false;
    for (var listener in _scantListeners) {
      listener.onStopScan();
    }
  }

  ///获取兼容的蓝牙设备
  CheckBleSupportInterface? getCheckBleSupportInterfaceForAddress(String address,{BleBeanInterface? bleBean}) {
    bleBean ??= getBleBean(address);
    if (bleBean != null) {
      //判断是否兼容
      for (var checkBleSupport in _checkBleSupport) {
        var bean = checkBleSupport.isSupport(bleBean);
        if (bean != null) {
          return checkBleSupport;
        }
      }
    }
  }

  ///扫描结果
  @override
  void onScanResult(result) {
    BleBeanInterface b = BleBeanInterface()
      ..name = result["name"]
      ..address = result["address"]
      ..bytes = result["bytes"]
      ..rssi = result["rssi"];

    //print("扫描结果:" + b.name+","+ jsonEncode(b.bytes));

    BleBeanInterface? bean;
    //判断是否兼容
    for (var checkBleSupport in _checkBleSupport) {
      bean = checkBleSupport.isSupport(b);
      if (bean != null) {
        break;
      }
    }
    if (bean == null) {
      return;
    }

    var indexOf = _bleBeans.indexOf(bean);
    if (indexOf == -1) {
      //这是新设备
      _bleBeans.add(bean);
    } else {
      //旧设备,更新一下数据旧可以了
      _bleBeans[indexOf] = bean;
    }

    for (var listener in _scantListeners) {
      listener.onScanResult(result);
    }
    notifyListener();
  }

  ///开始连接
  @override
  void onStartConnect(String address) {
    for (var listener in _connectListeners) {
      listener.onStartConnect(address);
    }
  }

  ///用mac地址获取蓝牙信息
  T? getBleBean<T extends BleBeanInterface>(String address) {
    BleBeanInterface bean = BleBeanInterface();
    bean.address = address;
    var indexOf = _bleBeans.indexOf(bean);
    if (indexOf != -1) {
      var b = _bleBeans[indexOf];
      if (b is T) {
        return b;
      }
    }
    return null;
  }


  ///连接成功
  @override
  void onConnected(String address) {

    var bean = getBleBean(address);
    if (bean == null) {
      return;
    }
    bean.isConnect = true;
    for (var listener in _connectListeners) {
      listener.onConnected(address);
    }
    isConnecting = false;
    notifyListener();
  }

  ///连接失败
  @override
  void onDisconnected(String address) {

    var bean = getBleBean(address);
    if (bean == null) {
      return;
    }
    bean.isConnect = false;
    for (var listener in _connectListeners) {
      listener.onDisconnected(address);
    }
    isConnecting = false;
    notifyListener();
  }

  @override
  void onMtuChanged(String address, int mtu) {
    var bean = getBleBean(address);
    if (bean == null) {
      return;
    }
    bean.mtu = mtu;
    for (var listener in _connectListeners) {
      listener.onMtuChanged(address, mtu);
    }
    notifyListener();
  }

  void notifyListener();

  ///ota相关的回调

  /// 开始升级
  @override
  void onOtaStart() {
    for (var listener in _otaListeners) {
      listener.onOtaStart();
    }
  }

  /// 升级固件进度
  @override
  void onOtaBootLoaderProgress(int progress) {
    for (var listener in _otaListeners) {
      listener.onOtaBootLoaderProgress(progress);
    }
  }

  /// 升级进度
  @override
  void onOtaProgress(int progress) {
    for (var listener in _otaListeners) {
      listener.onOtaProgress(progress);
    }
  }

  /// 升级完成
  @override
  void onOtaSuccess() {
    for (var listener in _otaListeners) {
      listener.onOtaSuccess();
    }
  }

  /// 升级失败
  @override
  void onOtaFailed(String msg) {
    for (var listener in _otaListeners) {
      listener.onOtaFailed(msg);
    }
  }

  @override
  void onOtaAvailable(String address, String mac, bool isMandatoryUpgrade) {
    var bean = getBleBean(address);
    if (bean != null) {
      bean.mac = mac;
      if (!bean.isConnect) {
        onConnected(address);
      }
    }

    for (var listener in _otaListeners) {
      listener.onOtaAvailable(address, mac, isMandatoryUpgrade);
    }
  }

  ///设备发送过来的数
  @override
  void onDataReceived(String address, String uuid, Uint8List data) {
    for (var listener in _bleDataListeners) {
      listener.onDataReceived(address, uuid, data);
    }
  }

  ///获取已经连接的蓝牙对象
  List<BleBeanInterface> getConnectBleBeans() {
    List<BleBeanInterface> list = [];
    for (var bean in _bleBeans) {
      if (bean.isConnect) {
        list.add(bean);
      }
    }
    return list;
  }
}
